package com.cpr.demo.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Chen Panrui
 * created at 2021/9/8 16:38
 * Q: 为什么会有这个类？（验证 线程池在刚new出来的时候没有worker线程，真正使用的时候才会new一个worker线程[worker数量 < core的时候都会new一个出来]）
 * A: 验证：只有new Thread()的时候，主线程的itl会被赋值给子线程。
 */
public class InheritableThreadLocalTest2 {

    public static void main(String[] args) throws InterruptedException {
        InheritableThreadLocal<String> itl = new InheritableThreadLocal<>();
        // 先new Thread()
        Thread t1 = new Thread(() -> {
            System.out.println("子线程：itl=" + itl.get());
        });
        // 然后再设置itl
        itl.set("hello, cpr");
        System.out.println("main线程：itl=" + itl.get());
        TimeUnit.SECONDS.sleep(1);
        t1.start();

        // 区别------- ↑ new一个Thread ↑ ------- ↓ new一个线程池 ↓ -------

        itl.remove();
        // 先new ThreadPoolExecutor()
        ExecutorService executor = new ThreadPoolExecutor(1, 1, 300, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>());
        // 然后再设置itl
        itl.set("gg, cpr");
        executor.execute(()->{
            System.out.println("子线程：itl=" + itl.get());
        });
        System.out.println("main线程：itl=" + itl.get());
        executor.shutdown();

        // ----- 验证点：线程池初始化时，worker数量=0

        itl.remove();
        ExecutorService executor2 = new ThreadPoolExecutor(1, 1, 300, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>());
        // 先new一个worker线程
        executor2.execute(()->{
            System.out.println("-------");
        });
        // 然后在设置itl
        TimeUnit.SECONDS.sleep(1);
        itl.set("bye, cpr");
        executor2.execute(()->{
            System.out.println("子线程：itl=" + itl.get());
        });
        System.out.println("main线程：itl=" + itl.get());

    }
}
